package xyc.sjxy.exam.filter;

import xyc.sjxy.exam.pojo.Users;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(value = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//1、判断用户是否登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Users loginInfo = (Users) req.getSession().getAttribute("loginInfo");
        String requestURI = req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
         if (loginInfo==null && !requestURI.equalsIgnoreCase(req.getContextPath()+"/login.jsp")
       && !requestURI.equalsIgnoreCase(req.getContextPath()+"/user/login")) {
            //没有登录
            resp.sendRedirect(req.getContextPath()+"/Login.jsp");
        }
        //已登录 放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
